//
//  CourseCenterOrderViewController.m
//  xpkc
//
//  Created by TopSageOSX on 15/2/3.
//  Copyright (c) 2015年 TopSage. All rights reserved.
//

#import "CourseCenterOrderViewController.h"

#import "UserMessage.h"

#import "DeliveryAddressViewController.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APAuthV2Info.h"
#import "CartModel.h"
#import "StudyCardViewController.h"
@interface CourseCenterOrderViewController ()
{
    CourseCenterOrderView * _ccov;
    NSDictionary * _dict;
    BOOL _hasAddress;
    
}
@end

@implementation CourseCenterOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (IsIOS7) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    [self setTitle:@"生成订单"];
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1];
    [self creatNavItem];
    [self creatOrderView];
    [self getDefaultAddress];
    
    
   
}


-(void)getDefaultAddress{
    
    NSString *module = @"address";
    NSString *interface = @"myaddress";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString,@"userid":[UserMessage sharedUserMessage].userMid,@"pagecode":@"1"};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        logdebug(@"%@",dic);
        
        
        _dict = dic;
        
        
        [self performSelectorOnMainThread:@selector(updateData) withObject:nil waitUntilDone:YES];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       
        
        NSLog(@"%@",error);
    }];
    
    
}

// 设置收货地址
-(void)updateData{
    
    NSArray * infoArray = _dict[@"info"];
    for (NSDictionary * subDic in infoArray) {
        
        NSLog(@"%@",subDic);
        
        if ([subDic[@"isdefault"] intValue]) {
            
            _hasAddress = YES;
            [_ccov setRecipitentInfoWithDic:subDic];
            
            return;
            
        }
        
    }
    
    _hasAddress = NO;
    [_ccov setRecipitentInfoWithDic:@{}];
    
}


-(void)updateData:(NSDictionary *)dict{
    [_ccov setRecipitentInfoWithDic:dict];
}

#pragma mark -
#pragma mark == creatview ==
- (void)creatNavItem{
    UIImage *image = [UIImage imageNamed:@"back1"];
    if (IsIOS7) {
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStyleBordered target:self action:@selector(backtocart)];
    self.navigationItem.leftBarButtonItem = backItem;
}
- (void)creatOrderView{
    CourseCenterOrderView *CCOV = [[CourseCenterOrderView alloc]initWithFrame:self.view.bounds];
    _ccov = CCOV;
    

    [CCOV.recipientBtn addTarget:self action:@selector(setDefaultAdd) forControlEvents:UIControlEventTouchUpInside];
//    [CCOV setItemInfoWithArray:self.cartArray price:self.currenPrice studycard:self.downStudycard];
    [CCOV setItemInfoWithArray:self.cartArray price:self.currenPrice studycard:self.downStudycard array:self.myCartArray];
    NSDictionary * infoDic = [[NSUserDefaults standardUserDefaults] valueForKey:@"defaultAddressKey"];
    if (infoDic) {
        
        _hasAddress = YES;
        [CCOV setRecipitentInfoWithDic:infoDic];
    }else{
        
        [self getDefaultAddress];
    }
    
    // [CCOV setRecipitentInfoWithDic:@{}];
    CCOV.delegate = self;
    [self.view addSubview:CCOV];
    
//        [CCOV.studyButton addTarget:self action:@selector(uptopclick) forControlEvents:UIControlEventTouchUpInside];
}


-(void)uptopclick{
    
    NSLog(@"充值");
}

-(void)studyCardClick:(NSInteger)number{
    
//    NSLog(@"111222");
    
    StudyCardViewController * studyCard = [[StudyCardViewController alloc] init];
    
    studyCard.hidesBottomBarWhenPushed = YES;
    
    if (IsIOS7) {
        
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            
            
            self.navigationController.interactivePopGestureRecognizer.delegate = nil;
        }
        
    }
    
    
    if (number == 2) {
        
        studyCard.selectIndex = 1;
    }
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [self.navigationController pushViewController:studyCard animated:YES];
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    _hasAddress = NO;
    NSDictionary * infoDic = [[NSUserDefaults standardUserDefaults] valueForKey:@"defaultAddressKey"];
    if (infoDic.count > 0) {
        _hasAddress = YES;
        [_ccov setRecipitentInfoWithDic:infoDic];
    }else{
        
        [self getDefaultAddress];
    }
    
    [_ccov setRecipitentInfoWithDic:infoDic];
}

//跳转学习卡
-(void)studyButton1
{
    NSLog(@"111222");
    StudyCardViewController * studyCard = [[StudyCardViewController alloc] init];
    
    studyCard.hidesBottomBarWhenPushed = YES;
    
    if (IsIOS7) {
        
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            
            
            self.navigationController.interactivePopGestureRecognizer.delegate = nil;
        }
        
    }
    
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [self.navigationController pushViewController:studyCard animated:YES];
}

// 设置默认收货地址
-(void)setDefaultAdd{
    
    NSLog(@"设置默认收货地址");
    
    DeliveryAddressViewController * deliveryVC = [[DeliveryAddressViewController alloc] init];
    
    [self.navigationController pushViewController:deliveryVC animated:YES];
}

#pragma mark -
#pragma mark == dunc ==
- (void)backtocart{
    [self.navigationController popViewControllerAnimated:YES];
}




#pragma mark - delegate
- (void)submitOrderwith:(NSString *)price andcredits:(NSString *)credits andoid:(NSString *)oid{
    
    
   
    logdebug(@"提交订单");
    
    
    if (!_hasAddress) {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"您还没选择收货地址" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:@"取消", nil];
        
        [alert show];
        
        return;
    }else{
        
       
       
        
        
        
        
    
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *partner = @"2088911290438885";
    NSString *seller = @"2928574672@qq.com";
    NSString *privateKey = @"MIICXQIBAAKBgQDtQz7mv0NiToJNsyCUqJ+nuRG39eu4SjCA6aKx35Lb+knV8Kbvk8O8rShk3pU1Dv8lzTTK8L/OMispgCEYaY8J8CysmR6ZXG0YpkiZGPwgYBN1G/QU5ll+9B+cFO9tuuKcBbiVXSAKw6ZtLbY6g4TNCjYA15fwtEX741wETAGEywIDAQABAoGBAJJGJv1zZUOySztD+A4ud1+cBYR4pL6VXpnbcGZhA9WC1QqEtyZ03vPvfTvSzgJMIJlZjfafvmCNJXcMe1rlmTzDWv3NTYzKL34QS/FEfNiyC8SEk2dPegn+BBDTMfePUwX36akXc/uGXOamd1O6NYZzO82cvTq2HEDFlNNPlNaBAkEA+tIf5Y7m2wk2Rj0qnoWCsL9MBmC51RV08ZHDR5+4uI0EJ0W6Dfp9b+PZCLwqE7G+FMJkywtaKzbX51sJUDuJ0QJBAPIpc256RLECgs3feaCERNXzOotMkhIx6KgqDKkaNrYvPVJMbcPmWby7eddi34nYRm6ba2+M3sueflL/74aBb9sCQAdBnPqfL76WfaN6kYkUg7tpTWHB2p53iHKUrPmdfVKZgc1BDyjoXkimZtkB2JXJRp6DITdelLU7WPOwhoxzrIECQQC8cJEIqVCGxcNv3LTSudqu+oTWHRGV4wx+v6n2dRWaE4yOXDcWOEwgV2rqtl/o7klwjLS/q0k7/eujPtHvQw39AkAXr1cZG7wy91zqQkxHM+e6QycXbiNJhwaP9fSWN/wPFbvzu6wyXkgbGCvrmhogjM9NpdCHtTqAwuD09rJZF0mx";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
        
        

       
        
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = oid; //订单ID（由商家自行制定）
       
        
        for (int i = 0; i<self.cartArray.count; i++) {
            CartModel *model =self.cartArray[i];
            
                    if (self.cartArray.count==1) {
                        order.productName = model.title; //商品标题
                        order.productDescription = model.title; //商品描述
                    }else{
                        order.productName = [NSString stringWithFormat:@"大家网%lu件商品",(unsigned long)self.cartArray.count]; //商品标题
                        order.productDescription = [NSString stringWithFormat:@"大家网%lu件商品",(unsigned long)self.cartArray.count]; //商品描述
                    }
            
        }


    
    order.amount = [NSString stringWithFormat:@"%.2f",[price doubleValue]]; //商品价格
    order.notifyURL = [NSString stringWithFormat:@"%@/laravel/public/payEnd/paysuccess?order_no=%@&pay=%@",URL2,oid,price]; //回调URL
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"xpkc";
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            
            NSLog(@"reslut = %@",resultDic);
            
//            if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]) {
//                
//                
//                NSLog(@"kouqian");
//                [self downPriceswith:[credits doubleValue]];
//                
//            }
            
        }];
        
        
    }
    
    
    
    }
    
    
    
    
    
}



//-(void)downPriceswith:(double)credit
//{
//    NSString *module = @"shopcar";
//    NSString *interface = @"jiancredits";
//    
//    NSString *timeString = [GetTime getTime];
//    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
//    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
//    
//    NSDictionary *parameter = @{@"time":timeString,@"username":[UserMessage sharedUserMessage].userId,@"amount":[NSString stringWithFormat:@"%f",credit]};
//    
//    //POST请求
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//    }];
//    
//}

#pragma mark -
#pragma mark == other ==
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
